import { Message } from "element-ui";
const doFetch = (api, option = {}) => {
    const prefix = 'http://127.0.0.1:5000/api';
    const {
        ...opt
    } = option;

    // if (opt.headers) {
    //     for(item in opt.headers) {
    //         console.log(item);
    //     }
    // } else {
    //     opt.headers = {
    //         'Content-type': 'application/json'
    //     }
    // }

    opt.headers = {
        ...opt.headers,
        'Content-type': 'application/json',
        'X-TOKEN': localStorage.getItem('token')
    };

    return new Promise((resolve, reject) => {
        fetch (prefix + api, {
            ...opt,
            body: JSON.stringify(opt.body)
        }).then (res => {
            if (res.status === 200) {
                res.text().then(res => {
                    resolve(JSON.parse(res));
                })
            } else {
                res.text().then(() => {
                    Message.error('服务未响应')
                })
            }
        }).catch((err) => {
            reject(err);
            Message.error('服务端异常，请联系管理员')
        })
    })
}

const request = (api, option) => {
    if (!option) {
        option = {
            method: 'GET'
        }
    }
    return doFetch(api, option)
}

export default request;